<template>
  <div class="combination-container">
    <div class="header">
      <el-row>
        <el-col :span="2">
          <div class="order-number">序号</div>
        </el-col>
        <el-col :span="10">
          <div class="">父Id取值关联excel字段</div>
        </el-col>
        <el-col :span="10">
          <div class="">父Id取值关联表字段</div>
        </el-col>
        <el-col :span="2">
          <div class="">
            <el-button
              type="text"
              icon="el-icon-circle-plus"
              @click="handleAdd"
            ></el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="body">
      <el-row
        v-for="(row,index) in rowData"
        :key="row.id"
      >
        <el-col :span="2">
          <div class="">{{index+1}}</div>
        </el-col>
        <el-col :span="10">
          <el-input
            :value="row.relExcelField"
            clearable
            @clear="handleClearRelExcelField(row.id)"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleOpenRelExcelFieldDialog(row)"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="10">
          <el-input
            :value="row.relField"
            clearable
            @clear="handleClearRelField(row.id)"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleOpenRelFieldDialog(row)"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <div class="">
            <el-button
              type="text"
              icon="el-icon-remove"
              @click="handleDelete(row)"
            ></el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div v-show="validTip" class="el-form-item__error">{{validTip}}</div>
    <el-dialog
      v-dialog-drag
      width="50%"
      title="父Id取值关联excel字段"
      :visible.sync="relExcelFieldDialog.visible"
      :modal="true"
      :appendToBody="true"
      top="7vh"
      height="calc(100% - 47px)"
      custom-class="select-dialog"
    >
      <div class="tool-search">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="relExcelFieldDialog.keyword"
          clearable
          @keyup.enter.native="handleRelExcelTableSearch"
        >
        </el-input>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-search"
          @click="handleRelExcelTableSearch"
        >查询</el-button>
      </div>
      <div class="tool-table">
        <el-table
          ref="Table"
          :data="relExcelFieldDialog.displayTableData"
          stripe
          border
          tooltip-effect="dark"
          style="width: 100%"
          height="calc(100% - 50px - 15px)"
          @select="handleTableSelect"
          @row-click="handleRowClick"
        >
          <el-table-column
            type="selection"
            width="55"
          >
          </el-table-column>
          <el-table-column
            v-for="col in relExcelFieldDialog.columns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            show-overflow-tooltip
            :min-width="col.minWidth"
          >
          </el-table-column>
        </el-table>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleFinishTableSelect"
        >确 定</el-button>
        <el-button @click="relExcelFieldDialog.visible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-dialog-drag
      width="50%"
      title="父Id取值关联表字段"
      :visible.sync="relFieldDialog.visible"
      :modal="true"
      :appendToBody="true"
      top="7vh"
      height="calc(100% - 47px)"
      custom-class="select-dialog"
    >
      <div class="tool-search">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="relFieldDialog.keyword"
          clearable
          @keyup.enter.native="handleRelFieldTableSearch"
        >
        </el-input>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-search"
          @click="handleRelFieldTableSearch"
        >查询</el-button>
      </div>
      <div class="tool-table">
        <el-table
          ref="relFieldTable"
          :data="relFieldDialog.tableData"
          stripe
          border
          tooltip-effect="dark"
          style="width: 100%"
          height="calc(100% - 50px - 15px)"
          @select="handleRelFieldTableSelect"
          @row-click="handleRelFieldRowClick"
        >
          <el-table-column
            type="selection"
            width="55"
          >
          </el-table-column>
          <el-table-column
            v-for="col in relFieldDialog.columns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            show-overflow-tooltip
            :min-width="col.minWidth"
          >
          </el-table-column>
        </el-table>
        <div class="pagination">
          <pagination
            v-show="relFieldDialog.pager.total>0"
            :total="relFieldDialog.pager.total"
            :page.sync="relFieldDialog.pager.pageNum"
            :limit.sync="relFieldDialog.pager.pageSize"
            @pagination="handleRelFieldPageChange"
          />
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleFinishRelFieldTableSelect"
        >确 定</el-button>
        <el-button @click="relFieldDialog.visible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getFieldListByTable } from '@/api/import/template'
export default {
  props: {
    attrs: {
      type: Object,
      default: () => ({})
    },
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rowData: [],
      relExcelFieldDialog: {
        item: {},
        visible: false,
        keyword: '',
        columns: [
          {
            prop: 'excelColumnCode',
            label: '字段名',
            minWidth: '100'
          },
          {
            prop: 'excelColumnName',
            label: '描述',
            minWidth: '100'
          }
        ],
        tableData: [],
        displayTableData: []
      },
      relFieldDialog: {
        item: {},
        visible: false,
        keyword: '',
        columns: [
          {
            prop: 'fieldCode',
            label: '字段名',
            minWidth: '100'
          },
          {
            prop: 'fieldName',
            label: '描述',
            minWidth: '100'
          }
        ],
        tableData: [],
        pager: {
          total: 0,
          pageNum: 1,
          pageSize: 10
        }
      },
      validTip: ''
    }
  },
  computed: {
    tableName() {
      return this.attrs.tableName || ''
    },
    defaultValue() {
      return this.attrs.defaultValue
    },
    fieldList() {
      return this.attrs.fieldList
    }
  },
  methods: {
    emitChange() {
      // relExcelField与relField必须同时存在
      const rowDataValues = this.rowData.filter(
        (ele) => ele.relExcelField && ele.relField
      )
      this.$emit('change', rowDataValues)
    },
    // 添加行
    handleAdd() {
      this.rowData.push({
        id: new Date().getTime(),
        relExcelField: '',
        relField: ''
      })
    },
    // 删除行
    handleDelete(row) {
      this.rowData = this.rowData.filter((ele) => {
        return ele.id !== row.id
      })
      this.validate()
      this.emitChange()
    },
    handleClearRelExcelField(id) {
      const row = this.rowData.find((ele) => ele.id === id)
      if (row) {
        row.relExcelField = ''
      }
      this.emitChange()
    },
    handleClearRelField(id) {
      const row = this.rowData.find((ele) => ele.id === id)
      if (row) {
        row.relField = ''
      }
      this.emitChange()
    },
    // 打开excel关联字段选择弹框
    handleOpenRelExcelFieldDialog(row) {
      this.relExcelFieldDialog.visible = true
      this.relExcelFieldDialog.item = { ...row }
      this.relExcelFieldDialog.tableData = [...this.fieldList]
      this.relExcelFieldDialog.displayTableData = [...this.relExcelFieldDialog.tableData]
    },
    // excel关联字段选择弹框 内容搜索
    handleRelExcelTableSearch() {
      this.relExcelFieldDialog.displayTableData = this.relExcelFieldDialog.tableData.filter(ele => {
        return ele.excelColumnCode.toLocaleLowerCase().includes(this.relExcelFieldDialog.keyword.toLocaleLowerCase())
      })
    },
    // 关联字段选择弹框 内容搜索
    handleRelFieldTableSearch() {
      this.relFieldDialog.pager.pageNum = 1
      const { pager: {pageNum, pageSize}, keyword } = this.relFieldDialog
      getFieldListByTable(
        this.tableName,
        pageNum,
        pageSize,
        keyword
      ).then((res) => {
        this.relFieldDialog.tableData = res.data.records
        this.relFieldDialog.pager.total = res.data.total
        this.relFieldDialog.visible = true
      })
    },
    // excel关联字段选择弹框 行点击
    handleRowClick(row) {
      this.tableSelectControl(row)
    },
    // excel关联字段选择弹框 行勾选
    handleTableSelect(selection, row) {
      this.tableSelectControl(row)
    },
    // excel关联字段选择弹框 行点击/行勾选进行选中
    tableSelectControl(row, refTable = 'Table', key = 'excelColumnCode') {
      // 单选
      row.flag = !row.flag
      this.$refs[refTable].clearSelection()
      this.relExcelFieldDialog.tableData.forEach((ele) => {
        if (ele[key] !== row[key]) {
          ele.flag = false
        }
      })
      this.$refs[refTable].toggleRowSelection(row, row.flag)
    },
    // excel关联字段弹框关闭，对行数据进行赋值
    handleFinishTableSelect() {
      const item = this.relExcelFieldDialog.item
      const selection = this.$refs.Table.selection
      if (!selection?.length) {
        return
      }
      let row = this.rowData.find((ele) => ele.id === item.id)
      row.relExcelField = selection[0].excelColumnCode
      this.relExcelFieldDialog.visible = false

      this.emitChange()
    },
    // 关联表字段选择弹框打开
    handleOpenRelFieldDialog(row) {
      this.relFieldDialog.item = { ...row }
      const { pageNum, pageSize, keyword } = this.relFieldDialog.pager
      getFieldListByTable(
        this.tableName,
        pageNum,
        pageSize,
        keyword
      ).then((res) => {
        this.relFieldDialog.tableData = res.data.records
        this.relFieldDialog.pager.total = res.data.total
        this.relFieldDialog.visible = true
      })
    },
    //关联表字段选择弹框 行点击
    handleRelFieldRowClick(row) {
      this.tableSelectControl(row, 'relFieldTable', 'fieldCode')
    },
    //关联表字段选择弹框 行勾选
    handleRelFieldTableSelect(selection, row) {
      this.tableSelectControl(row, 'relFieldTable', 'fieldCode')
    },
    handleRelFieldPageChange() {
      const { pageNum, pageSize, keyword } = this.relFieldDialog.pager
      getFieldListByTable(
        this.tableName,
        pageNum,
        pageSize,
        keyword
      ).then((res) => {
        this.relFieldDialog.tableData = res.data.records
        this.relFieldDialog.pager.total = res.data.total
      })
    },
    // 关联表字段弹框关闭，对行数据进行赋值
    handleFinishRelFieldTableSelect() {
      const item = this.relFieldDialog.item
      const selection = this.$refs.relFieldTable.selection
      if (!selection?.length) {
        return
      }
      let row = this.rowData.find((ele) => ele.id === item.id)
      row.relField = selection[0].fieldCode
      this.relFieldDialog.visible = false

      this.emitChange()
    },
    resetFields() {
      this.validTip = ''
      this.rowData = []
    },
    validate(callback) {
      const rows = this.rowData
      const emtyRow = rows.find((ele) => !ele.relField || !ele.relExcelField)
      if (emtyRow) {
        this.validTip = '【excel关联字段】与【关联表字段】必须一一配对'
        callback && callback(false)
      } else {
        this.validTip = ''
        callback && callback(true)
      }
    }
  },
  watch: {
    defaultValue: {
      handler(newVal) {
        if (!newVal?.length) {
          return
        }
        this.rowData = newVal
      },
      immediate: true
    }
  }
}
</script>
<style lang="less" scoped>
.combination-container {
  border: 1px solid #f0f0f0;
}
.el-col {
  min-height: 30px;
  text-align: center;
  padding: 5px 10px;
}
.header {
  background-color: #f0f0f0;
  padding-right: 10px;
  .order-number {
    min-width: 30px;
  }
}
.body {
  padding-right: 10px;
}
.select-dialog {
  .el-dialog__body {
    height: calc(69vh - 170px);
  }
}
.pagination {
  overflow: hidden;
  .pagination-container {
    margin-bottom: 0;
  }
}
.tool-search {
  display: flex;
  .el-input {
    width: 250px;
    margin-right: 10px;
  }
}
.tool-table {
  margin-top: 15px;
  height: calc(100% - 36px - 15px);
}
</style>